<template>
  <template v-if="getShow">
    <LoginFormTitle class="enter-x" />
    <Form class="p-4 enter-x" :model="formData" :rules="getFormRules" ref="formRef">
      <!-- tenantCode select -->
      <FormItem name="tenantCode" class="enter-x">
        <Select
          v-model:value="formData.tenantCode"
          size="large"
          :options="tenantCodeOptions"
          placeholder="机构"
        />
      </FormItem>
      <FormItem name="mobile" class="enter-x">
        <Input
          size="large"
          v-model:value="formData.mobile"
          :placeholder="t('sys.login.mobile')"
          class="fix-auto-fill"
        />
      </FormItem>
      <FormItem name="sms" class="enter-x">
        <CountdownInput
          size="large"
          class="fix-auto-fill"
          v-model:value="formData.sms"
          :sendCodeApi="beforeStartFunc"
          :placeholder="t('sys.login.smsCode')"
        />
      </FormItem>

      <FormItem class="enter-x">
        <Button type="primary" size="large" block @click="handleLogin" :loading="loading">
          {{ t('sys.login.loginButton') }}
        </Button>
        <Button size="large" block class="mt-4" @click="handleBackLogin">
          {{ t('sys.login.backSignIn') }}
        </Button>
      </FormItem>
    </Form>
  </template>
</template>
<script lang="ts" setup>
  import { reactive, ref, computed, unref } from 'vue';
  import { Form, Input, Button, Select } from 'ant-design-vue';
  import { CountdownInput } from '/@/components/CountDown';
  import LoginFormTitle from './LoginFormTitle.vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useLoginState, useFormRules, useFormValid, LoginStateEnum } from './useLogin';
  import { getTenantList } from '/@/api/sys/tenant';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { sendSmsApi } from '/@/api/sys/user';
  import { useUserStore } from '/@/store/modules/user';

  const { notification } = useMessage();

  const { createMessage } = useMessage();

  const FormItem = Form.Item;
  const { t } = useI18n();
  const { handleBackLogin, getLoginState } = useLoginState();
  const { getFormRules } = useFormRules();
  const error = createMessage.error!;

  const formRef = ref();
  const loading = ref(false);

  const formData = reactive({
    mobile: '',
    sms: '',
    tenantCode: 'hyy',
  });

  const { validForm } = useFormValid(formRef);

  const getShow = computed(() => unref(getLoginState) === LoginStateEnum.MOBILE);
  const userStore = useUserStore();

  async function handleLogin() {
    const data = await validForm();
    if (!data) return;

    try {
      loading.value = true;
      const userInfo = await userStore.mobileLogin({
        ...formData,
      });
      if (userInfo) {
        notification.success({
          message: t('sys.login.loginSuccessTitle'),
          description: `${t('sys.login.loginSuccessDesc')}: ${userInfo.name}`,
          duration: 3,
        });
      }
    } catch (error) {
      console.log('log ~ error:', error);
    } finally {
      loading.value = false;
    }
  }

  async function beforeStartFunc() {
    // 校验手机号
    if (!formData.mobile) {
      error('请输入手机号');
      return Promise.reject();
    } else if (!/^1[3456789]\d{9}$/.test(formData.mobile)) {
      error('请输入正确的手机号');
      return Promise.reject();
    }

    try {
      // 发送验证码
      await sendSmsApi(formData);
      return Promise.resolve(true);
    } catch (error) {
      return Promise.reject();
    }
  }

  // 查询机构信息
  const tenantCodeOptions = ref<any[]>([]);
  async function getTenantDataList() {
    // 查询全部
    const res = await getTenantList({
      pageSize: 1000,
      pageNum: 1,
      tenantCode: formData.tenantCode,
    });
    if (res) {
      tenantCodeOptions.value = res.list.map((item) => {
        return { label: item.tenantName, value: item.tenantCode };
      });
    }
  }

  getTenantDataList();
</script>
